<?php
class Controller_Online_Amazon extends Controller_Abstract
{
	function actionUpdate()
	{
		$this->_view['title'] = '更新上架数据';
		$this->_view['shop_group'] = Shop_User_Mapping::getTreeShopByPlatform(array('IAINSWAN', 'DAVIDSONNE', 'Orr', 'robertaspland', 'NNJYCE', 'shariwilliams', 'TODD'));
		if ($this->_context->isPOST())
		{
			$start_time = empty($_POST['start_time']) ? '' : date('c', strtotime($_POST['start_time']));
			$end_time = empty($_POST['end_time']) ? '' : date('c', strtotime($_POST['end_time'] . ' 23:59:59'));
			$result = Online_Amazon_Product::getOnlineAmazonProduct($_POST['shop_id'], $start_time, $end_time);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('更新成功', '正在返回..', $_SERVER['HTTP_REFERER']);
			}
			else
			{
				return $this->_redirectMessage('更新失败', $result['message'], $_SERVER['HTTP_REFERER']);
			}
		}
		if (isset($_GET['shop_ids']))
		{
			$amazon_shops = Shop_API_Amazon::find('shop_api_amazon.shop_id in (' . $_GET['shop_ids'] . ') and online_amazon_task.request_id is not NULL and online_amazon_task.report_id is NULL and online_amazon_task.request_time>=\'' . date('Y-m-d', CURRENT_TIMESTAMP) . '\'')
				->joinLeft('online_amazon_task', 'id as online_amazon_task_id, request_id', 'online_amazon_task.shop_id=shop_api_amazon.shop_id')
				->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
				->order('shop_id desc')
				->asArray()->getAll();
			Helper_BSS_API::getAmazonReportListId($amazon_shops);
		}
	}
	
	function actionList()
	{
		$this->_view['title'] = '产品上架列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 15;
		$purchase_categories = Product_Categories::getCategoriesTree();
		$this->_view['purchase_categories'] = json_encode($purchase_categories);
		$this->_view['shop_group'] = Shop_User_Mapping::getTreeShopByPlatform(array('IAINSWAN', 'DAVIDSONNE', 'Orr', 'robertaspland', 'NNJYCE', 'shariwilliams', 'TODD'));
		$url_arr =Helper_BSS_Normal::buildCondition();
		$this->_view['url_arr_json'] = json_encode($url_arr);
		if (isset($_GET['is_search']) && isset($_GET['shop_id']) && $_GET['shop_id'])
		{
			$result = Online_Amazon_Product::search($url_arr, $cp, $ps);
			if ($result['ack'] == SUCCESS)
			{
				$request_result = Online_Amazon_Product::getOnlineAmazonInstantData($_GET['shop_id'], $result['data']);
				if ($request_result['ack'] == SUCCESS)
				{
					$result = Online_Amazon_Product::search($url_arr, $cp, $ps);
				}
				Helper_BSS_Normal::getProductImgUrl($result['data'], 'product_number');
				$this->_view['products'] = $result['data'];
				$page = new Helper_BSS_Page($result['pagination'], url('Online::Amazon/List', $url_arr));
				$this->_view['page'] = $page->getPage();
			}
		}
	}

	function actionUpload()
	{
		$this->_view['title'] ='上传上架数据';
		if (! empty($_POST['ids']) && !empty($_GET['type']) && !empty($_GET['shop_id']))
		{
			$message = '';
			foreach ($_GET['shop_id'] as $s)
			{
				$check_in_db = Online_Amazon_Product::find('id in (?) and shop_id=?', explode(',', $_POST['ids']), $s)->asArray()->getAll();
				if ($check_in_db)
				{
					$xml = '<?xml version="1.0" encoding="UTF-8"?>';
					$xml .= '<AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
					$xml .= '<Header>';
					$xml .= '<DocumentVersion>1.01</DocumentVersion>';
					$xml .= '<MerchantIdentifier>' . $s . '</MerchantIdentifier>';
					$xml .= '</Header>';
					$err_msg = array();
					$new_xml = $feed_type = '';
					if ($_GET['type'] == 'price')
					{
						$xml .= '<MessageType>Price</MessageType>';
						$feed_type = '_POST_PRODUCT_PRICING_DATA_';
						foreach ($check_in_db as $k => $c)
						{
							$standard_price = $c['price'];
							if (isset($_POST['by_price']) && !empty($_POST['price']))
							{
								$standard_price = $_POST['price'];
							}
							elseif (isset($_POST['by_adjust']) && !empty($_POST['adjust_price']) && !empty($_POST['adjust_operate'])) 
							{
								eval("\$standard_price=$c[price]$_POST[adjust_operate]$_POST[adjust_price];");
							}
							elseif (isset($_POST['by_discount']) && !empty($_POST['discount']))
							{
								$discount_price = $c['listing_price'] * $_POST['discount'];
							}
							else
							{
								$err_msg[] = $c['sku'] . '：调价失败，提交价格有误！';
								continue;
							}
							$new_xml .= '<Message>';
							$new_xml .= '<MessageID>' . ++$k . '</MessageID>';
							$new_xml .= '<Price>';
							$new_xml .= '<SKU>' . $c['sku'] . '</SKU>';
							$new_xml .= '<StandardPrice currency="DEFAULT">' . $standard_price . '</StandardPrice>';
							if (isset($discount_price))
							{
								$start_date = empty($_POST['start_time']) ? date('c', time()) : date('c', strtotime($_POST['start_time']));
								$end_date = empty($_POST['end_time']) ? date('c', strtotime('+3 year')) : date('c', strtotime($_POST['end_time']));
								$new_xml .= '<Sale>';
								$new_xml .= '<StartDate>' . $start_date . '</StartDate>';
								$new_xml .= '<EndDate>' . $end_date . '</EndDate>';
								$new_xml .= '<SalePrice currency="DEFAULT">' . round($discount_price, 2) . '</SalePrice> ';
								$new_xml .= '</Sale>';
							}
							$new_xml .= '</Price>';
							$new_xml .= '</Message>';
						}
					}
					elseif ($_GET['type'] == 'quantity')
					{
						$xml .= '<MessageType>Inventory</MessageType>';
						$feed_type = '_POST_INVENTORY_AVAILABILITY_DATA_';
						foreach ($check_in_db as $k => $c)
						{
							if (isset($_POST['by_quantity']) && $_POST['quantity']>=0)
							{
								$quantity = $_POST['quantity'];
							}
							elseif (isset($_POST['by_adjust']) && !empty($_POST['adjust_quantity']) && !empty($_POST['adjust_operate'])) 
							{
								eval("\$quantity=$c[quantity]$_POST[adjust_operate]$_POST[adjust_quantity];");
							}
							else
							{
								$err_msg[] = $c['sku'] . '：调库存失败，提交库存有误！';
								continue;
							}
							$new_xml .= '<Message>';
							$new_xml .= '<MessageID>' . ++$k . '</MessageID>';
							$new_xml .= '<OperationType>Update</OperationType>';
							$new_xml .= '<Inventory>';
							$new_xml .= '<SKU>' . $c['sku'] . '</SKU>';
							$new_xml .= '<Quantity>' . $quantity . '</Quantity>';
							if (isset($_POST['by_latency']) && ! empty($_POST['latency']))
							{
								$new_xml .= '<FulfillmentLatency>' . $_POST['latency'] . '</FulfillmentLatency>';
							}
							$new_xml .= '</Inventory>';
							$new_xml .= '</Message>';
						}
					}
					else
					{
						return $this->_redirectMessage('上传失败', '类型参数数据错误', $_SERVER['HTTP_REFERER'], FAILURE);
					}
					if ($new_xml)
					{
						$result = Helper_BSS_API::submitFeedToAmazon($s, $xml.$new_xml.'</AmazonEnvelope>', $feed_type);
						if ($result['ack'] == SUCCESS)
						{
							$message .= '上传成功，查询ID为：' . $result['data'] . ' ！点击下面链接可查询上传处理结果！<a herf="' . url('Default::Public/GetAmazonFeedSubmissionResult') . '">或直接前往查询界面查询结果！</a><p><a href="' . url('Default::Public/GetAmazonFeedSubmissionResult', array('shop_id' => $s, 'id' => $result['data'])) . '">稍等片刻，点击这里查询上传结果！</a></p>';
						}
						else
						{
							$message .= '<p>' . $result['message'] . '</p>';
						}
					}
					else
					{
						return $this->_redirectMessage('上传失败', implode("\n", $err_msg), $_SERVER['HTTP_REFERER'], FAILURE);
					}
				}
			}
			if ($message)
			{
				header("Content-Type:text/html; charset=utf-8");
				echo $message;exit;
			}
		}
		else
		{
			return $this->_redirectMessage('上传失败', '提交信息有误', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionIndependentChangeProductPrice()
	{
		$this->_view['title'] = '独立修改产品价格';
		if ( ! empty($_GET['ids']))
		{
			$products = Online_Amazon_Product::find('id in (\'' . implode('\',\'', explode(',', $_GET['ids'])) . '\')')->asArray()->getAll();
			if ($products)
			{
				$check_shop_id = $products[0]['shop_id'];
				foreach ($products as $p)
				{
					if ($p['shop_id'] != $check_shop_id)
					{
						return $this->_redirectMessage('修改失败', '所选产品不在同一个店铺！', $_SERVER['HTTP_REFERER'], FAILURE);
					}
				}
				$this->_view['shop_id'] = $check_shop_id;
				$this->_view['products'] = $products;
			}
			else
			{
				return $this->_redirectMessage('修改失败', '找不到产品！', $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('修改失败', '请选择产品！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionIndependentChangeProductPriceSave()
	{
		$this->_view['title'] = '独立修改产品价格(保存)';
		if ( ! empty($_POST['ids']) && ! empty($_POST['change_price']) && ! empty($_POST['shop_id']))
		{
			$change_price = $_POST['change_price'];
			$shop_id = $_POST['shop_id'];
			$xml = '<?xml version="1.0" encoding="UTF-8"?>';
			$xml .= '<AmazonEnvelope xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
			$xml .= 	'<Header>';
			$xml .= 		'<DocumentVersion>1.01</DocumentVersion>';
			$xml .= 		'<MerchantIdentifier>' . $_POST['shop_id'] . '</MerchantIdentifier>';
			$xml .= 	'</Header>';
			$xml .= 	'<MessageType>Price</MessageType>';
			$message = array();
			$new_xml = '';
			$feed_type = '_POST_PRODUCT_PRICING_DATA_';
			$products = Online_Amazon_Product::find('id in (\'' . implode('\',\'', $_POST['ids']) . '\') and shop_id=\'' . $shop_id . '\'')->asArray()->getAll();
			foreach ($products as $k => $p)
			{
				if ( ! empty($change_price[$p['id']]))
				{
					$standard_price = $change_price[$p['id']];
					$new_xml .= '<Message>';
					$new_xml .= 	'<MessageID>' . ++ $k . '</MessageID>';
					$new_xml .= 	'<Price>';
					$new_xml .= 		'<SKU>' . $p['sku'] . '</SKU>';
					$new_xml .= 		'<StandardPrice currency="DEFAULT">' . $standard_price . '</StandardPrice>';
					$new_xml .= 	'</Price>';
					$new_xml .= '</Message>';
				}
				else
				{
					$message[] = $p['sku'] . '：调价失败，提交价格为空！';
					continue;
				}
			}
			if ($new_xml)
			{
				$xml .= $new_xml;
				$xml .= '</AmazonEnvelope>';
				$result = Helper_BSS_API::submitFeedToAmazon($shop_id, $xml, $feed_type);
				header("Content-Type:text/html; charset=utf-8");
				if ($result['ack'] == SUCCESS)
				{
					echo '上传成功，查询ID为：' . $result['data'] . ' ！点击下面链接可查询上传处理结果！<a href="' . url('Default::Public/GetAmazonFeedSubmissionResult') . '">或直接前往查询界面查询结果！</a><p><a href="' . url('Default::Public/GetAmazonFeedSubmissionResult', array('shop_id' => $shop_id, 'id' => $result['data'])) . '">稍等片刻，点击这里查询上传结果！</a></p>';
				}
				else
				{
					echo '<p>' . $result['message'] . '</p>';
				}
			}
			else
			{
				return $this->_redirectMessage('上传失败', implode("\n", $message), $_SERVER['HTTP_REFERER'], FAILURE);
			}
		}
		else
		{
			return $this->_redirectMessage('修改失败', '请选择产品！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionDetail()
	{
		$this->_view['title'] = '上架产品详细';
		if ($this->_context->isGET())
		{
			$result = Online_Amazon_Product::getMatchingProductForIdRequest($_GET['sku'], $_GET['shop_id']);
			if ($result['ack'] == SUCCESS)
			{
				$check_in_product_bind = Product_Bind::find('number=?', substr($_GET['sku'], 0, 7))->asArray()->getOne();
				if ($check_in_product_bind['id'])
				{
					$product_in_db = Product_Bind_Item::find('product_bind_item.product_bind_id=?', $check_in_product_bind['id'])
						->joinLeft('product_warehouse', 'sales_trend, sales_status, purchase_status, available_quantity', 'product_warehouse.product_basic_id=product_bind_item.product_basic_id and product_warehouse.warehouse_id=1')
						->joinLeft('product_basic', 'name, number', 'product_basic.id=product_bind_item.product_basic_id')
						->asArray()->getAll();
				}
				else
				{
					$product_in_db[] = Product_Basic::find('product_basic.number=?', substr($_GET['sku'], 0, 7))
						->joinLeft('product_warehouse', 'sales_trend, sales_status, purchase_status, available_quantity', 'product_warehouse.product_basic_id=product_basic.id and product_warehouse.warehouse_id=1')
						->asArray()->getOne();
				}
				Helper_BSS_Normal::getProductImgUrl($product_in_db);
				$this->_view['product'] = $product_in_db;
				$this->_view['listing'] = $result['data'];
			}
			else
			{
				return $this->_redirectMessage('即时获取失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionDownload()
	{
		$this->_view['title'] = '下载';
		set_time_limit(0);
		if (isset($_GET['url_arr_json']))
		{
			$url_arr = json_decode($_REQUEST['url_arr_json'], true);
			$result = Online_Amazon_Product::search($url_arr, 0, 0);
			$request_result = Online_Amazon_Product::getOnlineAmazonInstantData($url_arr['shop_id'], $result['data']);
			if ($request_result['ack'] == SUCCESS)
			{
				$result = Online_Amazon_Product::search($url_arr, 0, 0);
			}
			include Q::ini('custom_system/lib_dir').'PHPExcel.php';
			$phpexcel = new PHPExcel();
			$phpexcel->getProperties()->setCreator(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setLastModifiedBy(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setTitle("Amazon上架情况统计表");
			$phpexcel->getProperties()->setSubject("Amazon上架情况统计表");
			$phpexcel->getProperties()->setDescription("Amazon上架情况统计表-运营系统");
			$phpexcel->getProperties()->setKeywords("Amazon上架情况统计表");
			$phpexcel->getProperties()->setCategory("Amazon上架情况统计表");
			$phpexcel->setActiveSheetIndex(0);
			$phpexcel->getActiveSheet()->setTitle("Amazon上架情况统计表");
			$phpexcel->getActiveSheet()->setCellValue('A1', "所属店铺");
			$phpexcel->getActiveSheet()->setCellValue('B1', "SKU");
			$phpexcel->getActiveSheet()->setCellvalue('C1', '店铺ID');
			$phpexcel->getActiveSheet()->setCellvalue('D1', '产品名称');
			$phpexcel->getActiveSheet()->setCellValue('E1', "采购状态");
			$phpexcel->getActiveSheet()->setCellValue('F1', "销售状态");
			$phpexcel->getActiveSheet()->setCellValue('G1', "状态");
			$phpexcel->getActiveSheet()->setCellValue('H1', "系统库存");
			$phpexcel->getActiveSheet()->setCellValue('I1', "库存");
			$phpexcel->getActiveSheet()->setCellValue('J1', "配送渠道");
			$phpexcel->getActiveSheet()->setCellValue('K1', "折前价");
			$phpexcel->getActiveSheet()->setCellValue('L1', "折后价+shipping");
			$phpexcel->getActiveSheet()->setCellValue('M1', "更新打折价时间");
			$phpexcel->getActiveSheet()->setCellValue('N1', "竞争价+shipping");
			$phpexcel->getActiveSheet()->setCellValue('O1', "更新竞价时间");
			$phpexcel->getActiveSheet()->setCellValue('P1', "创建时间");
			$phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('F1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('G1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('H1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('I1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('J1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('K1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('L1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('M1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('N1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('O1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('P1')->getFont()->setBold(true);
			$i = 2;
			foreach ($result['data'] as $r)
			{
				$phpexcel->getActiveSheet()->setCellValue('A'.$i, $r['shop_name']);
				$phpexcel->getActiveSheet()->getCell('B'.$i)->setValueExplicit($r['sku'], PHPExcel_Cell_DataType::TYPE_STRING);
				$phpexcel->getActiveSheet()->setCellValue('C'.$i, $r['shop_item_id']);
				$phpexcel->getActiveSheet()->setCellValue('D'.$i, $r['product_name']);
				$phpexcel->getActiveSheet()->setCellValue('E'.$i, Helper_BSS_Normal::getIniOne('product_purchase_status', 'value', $r['purchase_status'], 'name'));
				$phpexcel->getActiveSheet()->setCellValue('F'.$i, Helper_BSS_Normal::getIniOne('product_sales_status', 'value', $r['sales_status'], 'name'));
				$phpexcel->getActiveSheet()->setCellValue('G'.$i, Helper_BSS_Normal::getIniOne('online_amazon_product_status', 'value', $r['status'], 'name'));
				$phpexcel->getActiveSheet()->setCellValue('H'.$i, $r['available_quantity']);
				$phpexcel->getActiveSheet()->setCellValue('I'.$i, $r['quantity']);
				$phpexcel->getActiveSheet()->setCellValue('J'.$i, $r['channel']);
				$phpexcel->getActiveSheet()->setCellValue('K'.$i, $r['price']);
				$phpexcel->getActiveSheet()->setCellValue('L'.$i, $r['listing_price'] . ($r['listing_price_shipping_fee'] ? '+'.$r['listing_price_shipping_fee']:''));
				$phpexcel->getActiveSheet()->setCellValue('M'.$i, $r['update_listing_price_time']);
				$phpexcel->getActiveSheet()->setCellValue('N'.$i, $r['competitive_price'] . ($r['competitive_price_shipping_fee'] ? '+'.$r['competitive_price_shipping_fee']:''));
				$phpexcel->getActiveSheet()->setCellValue('O'.$i, $r['update_competitive_price_time']);
				$phpexcel->getActiveSheet()->setCellValue('P'.$i, $r['open_time']);
				$i++;
			}
			$writer = new PHPExcel_Writer_Excel5($phpexcel);
			$file_name = 'online-amazon-' . date('YmdHis', CURRENT_TIMESTAMP) . '-' . CURRENT_USER_NAME . ".xls";
			header("Content-Type: application/vnd.ms-execl");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline;filename="'.$file_name.'"');
			header("Content-Transfer-Encoding: binary");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			$writer->save('php://output');
		}
	}
}